package org.redhat.auth.security.util;

import java.lang.reflect.Method;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.redhat.auth.security.core.AuthUserDetailService;
import org.redhat.auth.security.user.UserDetailInfo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 本类实现用户缓存管理
 * 
 * @author lingen.liu
 * 
 */
public class UserCacheUtil {

	private static Cache userCahce = CacheManagerUtil.getUserCache();;

	/* 获取userService,以便在用户修改，缓存清除后重新再次获取用户信息 */
	private static AuthUserDetailService userService;

	static {
		boolean error = true;
		if (error || (error = false)) {
			try {
				Class<?> clazz = Class
						.forName("com.dayatang.domain.InstanceFactory");
				Method method = clazz.getMethod("getInstance", Class.class);
				userService = (AuthUserDetailService) method.invoke(null,
						AuthUserDetailService.class);
			} catch (Exception e) {
				error = true;
			}
		}
		if (error || (error = false)) {
			try {
				ApplicationContext ctx = new ClassPathXmlApplicationContext(
						"spring/security-context.xml");
				userService = ctx.getBean(AuthUserDetailService.class);
			} catch (Exception e) {
				error = true;
			}
		}
		if (error || (error = false)) {
			try {
				ApplicationContext ctx = new ClassPathXmlApplicationContext(
						"META-INF/spring/security-context.xml");
				userService = ctx.getBean(AuthUserDetailService.class);
			} catch (Exception e) {
				error = true;
			}
		}
	}

	/**
	 * 按名称清除指定用户缓存
	 * 
	 * @param username
	 */
	public static void removeCacheByUserName(String username) {
		if (userCahce != null) {
			userCahce.remove(username);
		}
	}

	/**
	 * 重新更新用户缓存，此方法在加载登录自定义属性时非常有用
	 * @param name
	 * @param userDetail
	 */
	public static void updateUserCache(UserDetailInfo userDetail) {
		if (userCahce != null) {
			Element element = new Element(userDetail.getUsername(), userDetail);
			userCahce.put(element);
		}
	}

	/**
	 * 清除所有用户信息的缓存
	 */
	public static void removeAllUserCache() {
		if (userCahce != null)
			userCahce.removeAll();
	}

	/**
	 * 从缓存中获取用户
	 * 
	 * @param username
	 * @return
	 */
	public static UserDetailInfo getUserInfo(String username) {
		UserDetailInfo user = null;
		if (userCahce != null) {
			Element element = userCahce.get(username);
			if (element != null)
				user = (UserDetailInfo) element.getValue();
		}

		if (user == null) {
			user = (UserDetailInfo) userService.loadUserByUsername(username);
		}
		return user;
	}

}